using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

namespace AOT.Game.Misc
{
    public static class Utils
    {
        /// <summary>
        /// 替换所有.为/除了最后一个
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ReplaceDotWithSlashExceptLast(string input)
        {
            // 找到最后一个点的索引
            int lastIndex = input.LastIndexOf('.');

            // 如果未找到点，则直接返回原始字符串
            if (lastIndex == -1)
            {
                return input;
            }

            // 使用 StringBuilder 来构建替换后的字符串
            StringBuilder resultBuilder = new StringBuilder();

            // 遍历字符串，替换除最后一个点之外的所有点
            for (int i = 0; i < input.Length; i++)
            {
                if (input[i] == '.' && i != lastIndex)
                {
                    resultBuilder.Append('/');
                }
                else
                {
                    resultBuilder.Append(input[i]);
                }
            }

            // 返回替换后的字符串
            return resultBuilder.ToString();
        }

        /// <summary>
        /// 根据文件生成md5码
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetFileMD5(string filePath)
        {
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] md5Info = md5.ComputeHash(fileStream);
                fileStream.Close();

                StringBuilder res = new StringBuilder();
                for (int i = 0; i < md5Info.Length; i++)
                {
                    res.Append(md5Info[i].ToString("x2"));
                }

                return res.ToString();
            }
        }

        /// <summary>
        /// 获取资源的最近一层文件夹路径
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public static string GetNearestFolder(string assetPath)
        {
            var str = assetPath.Split("/");
            StringBuilder sb = new StringBuilder();
            if (str.Length >= 1) sb.Append(str[0]);
            for (int i = 1; i < str.Length - 1; i++)
            {
                sb.Append("_" + str[i]);
            }

            return sb.ToString();
        }

        public static void SaveFileToDisk(byte[] bytes, string localPath)
        {
            if (bytes == null || bytes.Length == 0)
            {
                Debug.LogError("保存文件出错: 字节数组为空或长度为零");
                return;
            }

            try
            {
                // 确保目录存在
                string directoryPath = Path.GetDirectoryName(localPath);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                // 检查是否有写入权限
                if (!HasWritePermissionOnDir(directoryPath))
                {
                    Debug.LogError("没有对目标目录的写入权限: " + directoryPath);
                    return;
                }

                // 保存文件到本地磁盘
                File.WriteAllBytes(localPath, bytes);
                Debug.Log("文件保存成功: " + localPath);
            }
            catch (UnauthorizedAccessException uaEx)
            {
                Debug.LogError("访问被拒绝: " + uaEx.Message);
            }
            catch (IOException ioEx)
            {
                Debug.LogError("保存文件出错: " + ioEx.Message);
            }
            catch (System.Exception ex)
            {
                Debug.LogError("保存文件时发生未知错误: " + ex.Message);
            }
        }

        private static bool HasWritePermissionOnDir(string path)
        {
            try
            {
                using (FileStream fs = File.Create(
                           Path.Combine(path, Path.GetRandomFileName()),
                           1,
                           FileOptions.DeleteOnClose))
                {
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static (bool, string) ReadFileFromDisk(string localPath)
        {
            if (string.IsNullOrEmpty(localPath))
            {
                Debug.LogWarning("本地路径为空或无效");
                return default;
            }

            if (!File.Exists(localPath))
            {
                Debug.LogWarning("文件不存在: " + localPath);
                return default;
            }

            return (true, File.ReadAllText(localPath));
        }

        /// <summary>
        /// 通过相对路径，得到相对于项目地址的路径，主要用于打包
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetNowFullPath(string path)
        {
            var path2 = Path.Combine(Application.dataPath, "../../" + path);
            path2 = Path.GetFullPath(path2); // 获取绝对路径
            return path2;
        }
    }
}